﻿using Codemonk.Pease.Common;
using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace Codemonk.Pease.Server.Serialization
{
    public class XmlSerializater : ISerializater<string>
    {
        public string Serialize(object obj)
        {
            try
            {
                Type typePer = obj.GetType();
                XmlSerializer xmlSer = new XmlSerializer(typePer);
                StringBuilder sb = new StringBuilder();
                using (StringWriter tw = new StringWriter(sb))
                {
                    xmlSer.Serialize(tw, obj);
                    tw.Close();
                }
                return sb.ToString();
            }
            catch
            {
                return string.Empty;
            }
        }

        public B Deserialize<B>(string data)
        {
            try
            {
                Type typePer = typeof(B);
                XmlSerializer xmlSer = new XmlSerializer(typePer);
                using (var reader = new StringReader(data))
                {
                    return (B)xmlSer.Deserialize(reader);
                }
            }
            catch
            {
                return default(B);
            }
        }
    }
}
